﻿namespace CatClient.Message.Spi.Heartbeat.Extend
{
    using CatClient.Util;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    public class CpuInfo : HeartbeatExtention, IDisposable, IProcessPerformance
    {
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private readonly PerformanceCounter _process;
        private readonly PerformanceCounter _cpu;
        private readonly Dictionary<string, double> _dict;
        private static readonly int ProcessorCount = Environment.ProcessorCount;

        public CpuInfo()
        {
            this._stopwatch.Start();
            this._cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            this._process = this.CurrentProcessCounter("% Processor Time");
            this._dict = new Dictionary<string, double>();
            this._stopwatch.Stop();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info($"Heartbeat {"CpuInfo"} init finish. {this._stopwatch.ElapsedMilliseconds}ms");
        }

        public void Dispose()
        {
            if (this._process != null)
            {
                this._process.Dispose();
            }
            if (this._cpu != null)
            {
                this._cpu.Dispose();
            }
            GC.SuppressFinalize(this);
        }

        public override void Refresh()
        {
            this._stopwatch.Restart();
            this._dict.Clear();
            float num = this._process.NextValue();
            float num2 = this._cpu.NextValue();
            this._dict["Total"] = num2;
            this._dict["Process"] = num / ((float) ProcessorCount);
            this._stopwatch.Stop();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info($"Heartbeat {"CpuInfo"} refresh finish. {this._stopwatch.ElapsedMilliseconds}ms");
        }

        public override string Id =>
            "Cpu";

        public override Dictionary<string, double> Dict =>
            this._dict;
    }
}

